#include "../Mylog.h"
enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY,
};
class RolltimeSink : public mylog::Logsink
{
public:
    RolltimeSink(const std::string &basename, TimeGap gat_type) : _basename(basename)
    {
        switch (gat_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 2;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        _cur_gap = mylog::DateUtil::Now() / _gap_size;
        std::string pathname = CreateNewfile();
        mylog::FileUtil::CreateDirectory(mylog::FileUtil::Getpath(pathname));
        _ofs.open(pathname, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    void Log(const char *data, size_t len)
    {
        time_t cur = mylog::DateUtil::Now();
        if ((cur / _gap_size) != _cur_gap)
        {
            _cur_gap = cur / _gap_size;
            _ofs.close();
            std::string pathname = CreateNewfile();
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data, len);
        assert(_ofs.is_open());
    }

private:
    std::string CreateNewfile()
    {
        time_t t = mylog::DateUtil::Now();
        struct tm lm;
        localtime_r(&t, &lm);
        std::stringstream ss;
        ss << _basename;
        ss << lm.tm_year + 1900;
        ss << lm.tm_mon + 1;
        ss << lm.tm_mday;
        ss << lm.tm_hour;
        ss << lm.tm_min;
        ss << lm.tm_sec;
        ss << ".log";
        return ss.str();
    }

private:
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;  // 当前是第几个时间段
    size_t _gap_size; // 时间段的大小
};


int main()
{
    std::unique_ptr<mylog::LoggerBuilder> builder(new mylog::GlobalLoggerBuilder());
    builder->BuildLoggerLevel(mylog::LogLevel::value::WARN);
    builder->BuildLoggerName("async_logger");
    builder->BuildFormatter("[%c][%f:%l]%m%n");
    builder->BuildSink<RolltimeSink>("./logfile/roll-async-by-size", TimeGap::GAP_SECOND);
    builder->BuildLoggerType(mylog::LoggerType::LOGGER_ASYNC);
    mylog::Logger::ptr logger = builder->Build();
    time_t cur = mylog::DateUtil::Now();
    while(mylog::DateUtil::Now() < cur + 6)
    {
        logger->fatal("%s", "这是一条测试日志");
    }
    
    return 0;
}